package com.zoe.onelink.mybatis.interceptor.impl;

import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.zoe.onelink.common.entity.IBaseEntity;
import com.zoe.onelink.mybatis.interceptor.MybatisEntityUpdateInterceptor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;

import java.util.List;
import java.util.Map;

/**
 * <p>标题: 使用wrapper方式进行插入或更新操作时,进行拦截</p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2021</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: ruansheng
 * @date: 2021-03-23
 */
@Slf4j
@Intercepts({@Signature(
        type = Executor.class,
        method = "update",
        args = {MappedStatement.class, Object.class}
)})
@RequiredArgsConstructor
public class MybatisEntityUpdateInterceptorDispatcher implements Interceptor {

    private final List<MybatisEntityUpdateInterceptor> mybatisEntityUpdateInterceptors;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        // 没有对应的拦截器直接返回
        if (this.mybatisEntityUpdateInterceptors == null || this.mybatisEntityUpdateInterceptors.size() == 0) {
            return invocation.proceed();
        }
        Object target = invocation.getTarget();
        Object paramObj = invocation.getArgs()[1];
        if (!(target instanceof Executor)) {
            return invocation.proceed();
        }
        try {
            IBaseEntity entity = null;
            // 更新操作
            if (paramObj instanceof Map) {
                @SuppressWarnings("unchecked") Map<String, Object> parameter = (Map<String, Object>) paramObj;
                // 使用wrapper方式的情况下
                if (parameter.containsKey(Constants.ENTITY)) {
                    Object targetEntity = parameter.get(Constants.ENTITY);
                    if (targetEntity instanceof IBaseEntity) {
                        entity = (IBaseEntity) targetEntity;
                    }
                }
                // 插入操作(wrapper方式)
            } else if (paramObj instanceof IBaseEntity) {
                entity = (IBaseEntity) paramObj;
            }
            if (entity != null) {
                IBaseEntity finalEntity = entity;
                this.mybatisEntityUpdateInterceptors.forEach(interceptor -> interceptor.onUpdate(finalEntity));
            }
        } catch (Exception e) {
            this.onException(e);
        }
        return invocation.proceed();
    }

    protected void onException(Exception e) {
        log.warn("自动填充失败", e);
    }
}
